package com.example.host.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.example.host.config.MqttConfig;
import com.example.host.service.RemoteControlService;
import com.example.host.utils.AbsolutePathGetter;
import com.example.host.utils.SessionInfoUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.awt.*;
import java.net.URI;


@Service
@Slf4j
public class RemoteControlServiceImpl implements RemoteControlService {
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    AbsolutePathGetter absolutePathGetter;
    @Autowired
    SessionInfoUtils sessionInfoUtils;
    @Autowired
    MqttConfig mqttClient;
    @Value("${path.htmlFilePath}")
    String relativeHtmlPath;
    @Value("${mqtt.topic.remoteControlTopic}")
    String remoteControlTopic;
    
    //  通过公网IP进行指令发送
    @Override
    public JSONObject remoteConnect(String remoteDevicePublicIP) {
        String url = remoteDevicePublicIP + "/installService";
        JSONObject clientSessionInfo = restTemplate.postForObject(url, "InstallService", JSONObject.class);
        return clientSessionInfo;
    }

    @Override
    public String remoteDisConnect(String remoteDevicePublicIP) {
        String url = remoteDevicePublicIP + "/uninstallService";
        String response = restTemplate.postForObject(url, "UninstallService", String.class);
        return response;
    }
    //  通过MQTT进行指令发送
    @Override
    public JSONObject mqttRemoteConnect(String deviceName) {
        // 此处为了方便测试直接进行赋值，放到系统上时需把该赋值语句去除
        deviceName = "dachuan";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("deviceName",deviceName);
        jsonObject.put("instruction","install");
        String mqttInstruction = jsonObject.toJSONString();
        try {
            mqttClient.publish(0,false,remoteControlTopic,mqttInstruction);
            int timeCounter = 0;
            while (!sessionInfoUtils.isInstallSuccess(deviceName)){
                Thread.sleep(100);
                timeCounter += 100;
                if (timeCounter > 3500){
                    throw new RuntimeException("远控发起失败！");
                }
            }
            JSONObject sessionInfo = sessionInfoUtils.getSessionInfo(deviceName);
            sessionInfo.put("address",sessionInfo.getString("address"));
            sessionInfo.put("cid",sessionInfo.getString("cid"));
            return sessionInfo;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public String mqttRemoteDisconnect(String deviceName) {
        // 此处为了方便测试直接进行赋值，放到系统上时需把该赋值语句去除
        deviceName = "dachuan";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("deviceName",deviceName);
        jsonObject.put("instruction","uninstall");
        String mqttInstruction = jsonObject.toJSONString();
        try {
            mqttClient.publish(0,false,remoteControlTopic,mqttInstruction);
            int timeCounter = 0;
            while (sessionInfoUtils.isUninstallSuccess(deviceName)){
                Thread.sleep(100);
                timeCounter += 100;
                if (timeCounter > 3500){
                    throw new RuntimeException("远控断开失败！");
                }
            }
            log.info(sessionInfoUtils.getSessionInfo(deviceName).getString("msg"));
            sessionInfoUtils.deleteSessionInfo(deviceName);
            return "远控断开成功！";
        } catch (Exception e) {
            e.printStackTrace();
            return "远控断开失败！";
        }
    }

    @Override
    public void openRemoteHtml(JSONObject sessionInfo) {
        String address = (String) sessionInfo.get("address");
        String cid = (String) sessionInfo.get("cid");
        if (Desktop.isDesktopSupported()) {
            Desktop desktop = Desktop.getDesktop();
            try {
                String header = "file:///";
                String absoluteHtmlPath = absolutePathGetter.getAbsolutePath(relativeHtmlPath);
                String params = "?address=" + address + "&cid=" + cid;
                String path = header + absoluteHtmlPath + params;
                System.out.println(path);
                URI uri = new URI(path);
                desktop.browse(uri);


//                URI fileUri = new URI(header + absoluteHtmlPath);
//                String originalUrl = fileUri.toString();
//                String urlWithParams = originalUrl + "?" + "address=" + URLEncoder.encode(address,"UTF-8") + "&" + "cid=" + URLEncoder.encode(cid,"UTF-8");
//                URI uri = new URI(urlWithParams);
//                desktop.browse(uri);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
